package com.qf.servideimpl;

import com.qf.config.IdWorker;
import com.qf.constant.CacheConstants;
import com.qf.constant.RabbitMQConstants;
import com.qf.constant.ReportStateConstants;
import com.qf.constant.SourceType;
import com.qf.entity.SmsInterfaceForm;
import com.qf.enums.InterfaceExceptionEnums;
import com.qf.feign.CacheFeign;
import com.qf.model.StandardSubmit;
import com.qf.service.InterfaceService;
import com.qf.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author Ypl
 * @version V1.0
 * @Project OctoberAndNovember
 * @Package com.qf.servideimpl
 * @Description:
 * @Date 2022/11/9 20:08
 */
@SuppressWarnings("all")
@Service
@Slf4j
public class InterfaceServiceImpl implements InterfaceService {

    //远程调用
    @Autowired
    CacheFeign cacheFeign;

    @Autowired
    IdWorker idWorker;

    @Autowired
    RabbitTemplate rabbitTemplate;


    @Override
    public Result checkSmsInterfaceForm(SmsInterfaceForm smsInterfaceForm) {
        /**
         * 校验数据的合法性
         */
        Result result = checkParam(smsInterfaceForm);

        if(result != null){
            return result;
        }
        /**
         * 将数据发送到 RabbitMq 中
         *      要考虑到一个手机发送一个消息，有几个手机号发送几个
         */

        //获取客户端的手机号（可能是批量发送 多个手机号所以要切割）
        String mobile = smsInterfaceForm.getMobile();
        //切割
        String[] mobiles = mobile.split(",");
        //一个手机号发送一条短信
        for (String mobile1 : mobiles) {
            StandardSubmit submit = new StandardSubmit();
            //客户端ID
            submit.setClientID(Integer.parseInt(smsInterfaceForm.getClientID()));
            //下行编号 雪花算法生成
            submit.setSrcSequenceId(idWorker.nextId());
            //目的手机号
            submit.setDestMobile(mobile1);
            //消息内容
            submit.setMessageContent(smsInterfaceForm.getContent());

            submit.setSendTime(new Date());
            //消息来源
            submit.setSource(SourceType.HTTP);
            //发送的消息的状态
            submit.setReportState(ReportStateConstants.WAIT);

            log.debug("发送到消息队列：{}",submit);

            rabbitTemplate.convertAndSend(RabbitMQConstants.TOPIC_PRE_SEND,submit);
        }
        return Result.ok();
    }

    /**
     * 检验数据的合法性
     */
    private Result checkParam(SmsInterfaceForm smsInterfaceForm) {

        //获取客户端传来的ID
        String clientID = smsInterfaceForm.getClientID();

        //获取redis中的ID
        Map map = cacheFeign.hMGet(CacheConstants.CACHE_PREFIX_CLIENT + clientID);
        if(map == null || map.size() ==0){
            log.error("&redis 认证失败");
            return Result.error(InterfaceExceptionEnums.INTERFACE_CLIENT_ID_ERROR);
        }

        //获取redis中的pwd
        String pwd = (String) map.get("pwd");
        if(pwd == null || !pwd.equalsIgnoreCase(smsInterfaceForm.getPwd())){
            log.error("&redis 密码错误");
            return Result.error(InterfaceExceptionEnums.INTERFACE_PWD_ERROR);
        }


        if(smsInterfaceForm.getContent() == null || smsInterfaceForm.getContent().length() >500){
            log.error("&redis 消息长度错误");
            return Result.error(InterfaceExceptionEnums.INTERFACE_CONTENT_ERROR);
        }

        //获取redis中的ip
        String ipaddress = (String) map.get("ipaddress");
        if(ipaddress == null || !ipaddress.equalsIgnoreCase(smsInterfaceForm.getIp())){
            log.error("&redis ip错误");
            return Result.error(InterfaceExceptionEnums.INTERFACE_IP_ERROR);
        }

        //获取客户端的手机号（可能是批量发送 多个手机号所以要切割）
        String mobile = smsInterfaceForm.getMobile();
        //切割
        String[] mobiles = mobile.split(",");

        //最多只能给50个手机号发送短信
        if(mobiles.length>50 || mobile == null){
            log.error("&redis 手机号错误");
            return Result.error(InterfaceExceptionEnums.INTERFACE_MOBILE_ERROR);
        }

        //使用正则表达式校验用户的手机号是否正确
        String regex = "^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$";

        Set<String> errorMobiles = new HashSet<>();

        //遍历手机号，一个一个校验
        for (String mo : mobiles) {
            mo = mo.trim();
            if(!mo.matches(regex)){
                //将错误的手机号返回给客户端
                errorMobiles.add(mo);
            }
        }

        //返回错误的手机号列表
        if(errorMobiles.size() >0 ){
            return Result.error(105, "手机号错误，错误列表为" + errorMobiles);
        }

        return null;
    }
}
